
var fs = require('fs')
var util = require('../public/util')
let info = {
	getInfo: function(req, res) {
        fs.readFile("data.json", function(err, result) {
            let data = {};
            data.data = JSON.parse(result);
            data.code = "200";
            data.message = "数据查询成功"
            res.send(data);
        })
	},

    add:function(req, res) {
        let data = {};
        // req.body = {
        //     "name":"小李子",
        //     "tel":"13594359689",
        //     "address":"重庆市南岸去城南家园",
        //     "remark":"备注信息"
        // }
        fs.readFile("data.json", function(err, result) {
            let dataJson = JSON.parse(result);
            req.body.id = new Date().getTime();
            req.body.createTime = util.getNowFormatDate();
            req.body.updateTime = util.getNowFormatDate();
            dataJson.unshift(req.body);
            fs.writeFileSync("data.json",JSON.stringify(dataJson));
            data.code = "200";
            data.message = "添加成功";
            res.send(data);
        })
	},

    update: function(req, res) {
        let id = req.body.id;
        //id=1618640200434;
        let data = {};
        // req.body = {
        //     "name":"小李子2",
        //     "tel":"13594359689",
        //     "address":"重庆市南岸去城南家园",
        //     "remark":"备注信息"
        // }
        fs.readFile("data.json", function(err, result) {
            let dataJson = JSON.parse(result);
            req.body.updateTime = util.getNowFormatDate();
            let dataIndex = "";
            dataJson.forEach((item,index)=>{
                if(item.id == id) {
                    req.body.createTime = item.createTime;
                    dataIndex = index;
                }
            })
            dataJson[dataIndex] =  req.body;
            fs.writeFileSync("data.json",JSON.stringify(dataJson));
            data.code = "200";
            data.message = "修改成功";
            res.send(data);
        })
	},

    delete: function(req, res) {
        let id = req.query.id;
        //id=1618640200434;
        let data = {};
        fs.readFile("data.json", function(err, result) {
            let dataJson = JSON.parse(result);
            let dataIndex = "";
            dataJson.forEach((item,index)=>{
                if(item.id == id) {
                    dataIndex = index;
                }
            })
            dataJson.splice(dataIndex,1);
            fs.writeFileSync("data.json",JSON.stringify(dataJson));
            data.code = "200";
            data.message = "删除成功";
            res.send(data);
        })
	},
    
}

module.exports = info
